#!/usr/bin/env python
# coding:utf-8

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from crypt import *
from spider import *
from charts import *


class Robot(QWidget):

    def __init__(self):
        super(Robot, self).__init__()
        self.setWindowTitle("值班机器人")
        self.setFixedSize(240, 320)
        self.center()
        self.set_ui()
        self.mark = 1
        self.slide_mark = 1
        # self.setWindowFlags(Qt.CustomizeWindowHint)

    def set_ui(self):

        self.toolbar = QToolBar()
        self.toolbar.setStyleSheet('border:none;background-color:white;height:30px;')
        self.toolbar.setIconSize(QSize(20,20))

        self.display = QLineEdit()
        self.display.setText('00:00:00')
        self.display.setStyleSheet("height:200px;width:200px;background-image:url('./img/watch.ico');border:none;font-size:40px;")
        self.display.setAlignment(Qt.AlignCenter)
        self.display.setReadOnly(True)

        self.interval = QSlider(Qt.Horizontal)
        self.interval.setMinimum(0)
        self.interval.setMaximum(11)
        self.interval.setSingleStep(1)
        self.interval.setTickPosition(QSlider.NoTicks)
        self.interval.valueChanged.connect(self.reset)
        self.interval.sliderPressed.connect(self.slider_add)
        self.interval.setStyleSheet('height:26px;')

        self.timer = QTimer()
        self.timer.timeout.connect(self.show_time)


        self.setting_bnt = QAction(QIcon("./img/setting.png"),'设置',self)
        self.bnt = QAction(QIcon("./img/play.png"),'开始',self)
        self.html_bnt = QAction(QIcon("./img/html5.png"),'dashboard',self)
        self.close_bnt = QAction(QIcon("./img/close.png"),'关闭',self)

        self.setting_bnt.triggered.connect(self.setting)
        self.bnt.triggered.connect(self.start)
        self.html_bnt.triggered.connect(self.html)
        self.close_bnt.triggered.connect(lambda:os._exit(5))

        self.toolbar.addAction(self.bnt)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.html_bnt)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.setting_bnt)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.close_bnt)


        self.status_bar = QStatusBar()
        self.status_bar.setStyleSheet("width:20px;color:black;background-color:white;text-align:center;")
        self.status_bar.showMessage("建议关闭杀毒软件")

        # self.clock = 10*(1+self.interval.currentIndex())
        self.clock = 10*(1+int(self.interval.value()))
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.display)
        self.layout.addWidget(self.interval)
        # self.layout.addStretch()
        # self.layout.addWidget(self.bnt)
        # self.layout.addWidget(self.setting_bnt)
        # self.layout.addWidget(self.close_bnt)
        self.layout.addWidget(self.status_bar)

        self.setLayout(self.layout)

    def start(self):
        if self.mark:
            self.timer.start(1000)
            self.bnt.setIcon(QIcon("./img/pause.png"))
            self.bnt.setText('暂停')
            self.mark = 0
        else:
            self.timer.stop()
            self.bnt.setIcon(QIcon("./img/play.png"))
            self.bnt.setText('开始')
            self.mark = 1

    def reset(self):
        self.clock = 0
        self.status_bar.showMessage('设置时间间隔{}小时'.format(self.interval.value()+1))

    def slider_add(self):
        if self.interval.value() == 11:
            self.slide_mark = -1
        if self.interval.value() == 0:
            self.slide_mark = 1
        self.interval.setValue(self.interval.value()+self.slide_mark)

    def pause(self):
        self.timer.stop()
        self.bnt.setText("开始自动登录(ENT)")
        # self.bnt.clicked.disconnect(self.pause)
        # self.bnt.clicked.connect(self.start)
        self.bnt.triggered.disconnect(self.pause)
        self.bnt.triggered.connect(self.start)
        self.bnt = QAction(QIcon("./img/play.png"),'开始',self)

    def show_time(self):
        if self.clock:
            self.clock -= 1
            if not self.clock:
                now = datetime.datetime.now().hour
                if now < 22 and now > 7:
                    try:
                        self.t = Spider_Thread()
                        self.t.start()
                        self.t.spider_signal.connect(self.refresh_back_msg)

                    except Exception as e:
                        self.status_bar.showMessage('error!')
        else:
            now = datetime.datetime.now().hour
            if now > 22:
                self.clock = 3600*7
            elif now < 7:
                self.clock = 3600*(7-now)
            else:
                # self.clock = 3600*(1+self.interval.currentIndex())
                self.clock = 3600*(1+int(self.interval.value()))

        self.time = QTime(0,0,0)
        self.time2 = self.time.addSecs(self.clock)
        self.time3 = self.time2.toString('hh:mm:ss')
        self.display.setText(self.time3)

    def refresh_msg(self, msg):
        self.status_bar.showMessage(msg)

    def refresh_back_msg(self, msg):
        if msg:
            if self.interval.value():
                self.status_bar.showMessage(self.interval.value())
            else:
                self.status_bar.showMessage('爬取成功')
        else:
            self.status_bar.showMessage('爬取有误！')

        tmp = Gen_Charts()
        data = tmp.gen_data()
        tmp.dashboard(data)

    def html(self):
        os.startfile('dashboard.html')

    def setting(self):
        self.win= Setting()
        self.win.show()

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width() - self.size.width())/2),
                  int((self.screen.height() - self.size.height())/2)
                  )

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Return:
            self.start()
        if e.key() == Qt.Key_Escape:
            self.close()
        if e.key() == Qt.Key_F1:
            self.setting()

class Setting(QWidget):

    def __init__(self):
        super(Setting,self).__init__()
        self.setFixedSize(240, 200)
        self.center()
        self.con = sqlite3.connect("local.db")
        self.cur = self.con.cursor()
        self.setWindowTitle("证书设置")
        self.set_ui()

    def set_ui(self):
        self.username = QLineEdit()
        self.username.setPlaceholderText("输入大疫情对应权限用户名")
        self.username.setClearButtonEnabled(True)

        self.passwd2 = QLineEdit()
        self.passwd2.setPlaceholderText("数字证书密码")
        self.passwd2.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.passwd2.setClearButtonEnabled(True)
        self.username.setStyleSheet('height:30px;')
        self.passwd2.setStyleSheet('height:30px;')

        self.confirm_bnt = QPushButton("确定")
        self.clear_bnt = QPushButton("清空")
        self.close_bnt = QPushButton("关闭")
        self.reset_bnt = QPushButton("重置数据库")
        self.confirm_bnt.setStyleSheet('''background-color:'#66cc99'; border-style:outset;height:30px;color:white;''')
        self.clear_bnt.setStyleSheet('''background-color:'#0066cc'; border-style:outset; height:30px;color:white;''')
        self.close_bnt.setStyleSheet('''background-color:red; border-style:outset; height:30px;color:white;''')
        self.reset_bnt.setStyleSheet('''background-color:'#cc0033'; border-style:outset; height:30px;color:white;''')
        self.confirm_bnt.clicked.connect(self.confirm)
        self.clear_bnt.clicked.connect(self.clear_passwd)
        self.close_bnt.clicked.connect(self.close_win)
        self.reset_bnt.clicked.connect(self.reset)

        self.bnt_widget = QWidget()
        self.bnt_layout = QGridLayout()
        self.bnt_layout.addWidget(self.confirm_bnt,0,1,1,2)
        self.bnt_layout.addWidget(self.clear_bnt,0,0)
        self.bnt_layout.addWidget(self.reset_bnt,1,0,1,2)
        self.bnt_layout.addWidget(self.close_bnt,1,2)
        self.bnt_widget.setLayout(self.bnt_layout)

        self.mainlayout = QVBoxLayout()
        self.mainlayout.addWidget(self.username)
        self.mainlayout.addWidget(self.passwd2)
        self.mainlayout.addStretch()

        self.mainlayout.addWidget(self.bnt_widget)

        self.setLayout(self.mainlayout)


    def confirm(self):
        if self.passwd2.text() !=  '':
            if self.username.text() != '':
                vpn_sql = ''' update vpn set username = '{}' ,passwd = '{}'
                       where id = 1'''.format(encrypt(self.username.text()),encrypt(self.passwd2.text()))
            else:
                vpn_sql = ''' update vpn set passwd = '{}'
                       where id = 1'''.format(encrypt(self.passwd2.text()))
        elif self.username.text() !='' and self.passwd2.text() == '':
            vpn_sql = ''' update vpn set username = '{}'
                       where id = 1'''.format(encrypt(self.username.text()))
        else:
            vpn_sql = None
        if vpn_sql:
            self.cur.execute(vpn_sql)

        msg = QMessageBox.information(self, "提示",'确认修改',QMessageBox.Yes, QMessageBox.No)
        if msg == QMessageBox.Yes:
            self.con.commit()
        else:
            pass

    def clear_passwd(self):
        self.username.setText("")
        self.passwd2.setText("")
        self.username.setFocus()

    def close_win(self):
        self.con.close()
        self.close()

    def reset(self):
        self.cur.execute('delete from disease')
        msg = QMessageBox.information(self, "提示",'确认修改',QMessageBox.Yes, QMessageBox.No)
        if msg == QMessageBox.Yes:
            self.con.commit()
        else:
            pass

    def center(self):
        self.screen = QDesktopWidget().screenGeometry()
        self.size = self.geometry()
        self.move(int((self.screen.width() - self.size.width())/2),
                  int((self.screen.height() - self.size.height())/2)
                  )

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Return:
            self.confirm()
        if e.key() == Qt.Key_Escape:
            self.close()
        if e.key() == Qt.Key_F1:
            self.clear_passwd()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('./img/robot.png'))
    mainwindow = Robot()
    mainwindow.show()
    # mainwindow.start()
    sys.exit(app.exec_())
